package com.qk.management.web.filter;

import cn.hutool.core.util.ObjectUtil;

import com.qk.common.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @Author: ZgYn
 * @Date 2025/10/11 11:37
 * @name：LoginCheckFilter
 */

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    private static final String LOGIN_PATH = "/login";
    private static final String TOKEN_HEADER_NAME = "token";
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 1.判断是否登录
        String path = request.getRequestURI();

        if (ObjectUtil.equals(path, LOGIN_PATH)) {
            filterChain.doFilter(request, response);
            return;
        }
        String token = request.getHeader(TOKEN_HEADER_NAME);
        if (ObjectUtil.isEmpty(token)) {
            response.setStatus(401);
            return;
        }
        try{
            Claims claims = JwtUtils.parseToken(token);
            String username = claims.get("username", String.class);
            log.info("当前用户信息为:{}",username);
            Integer id = claims.get("id", Integer.class);
            log.info("当前用户id为:{}",id);
            filterChain.doFilter(servletRequest, servletResponse);
        }catch (Exception e){
            log.error("token解析失败",e);
            response.setStatus(401);
            return;
        }
    }
}
